<?php

class user extends controller_basic {
	
	function dashboard() { // 获取我捞到/扔出去的瓶子
		
		$sitemid	= isset($this->__params['sitemid'])	? $this->__params['sitemid'] : '';
		$time		= isset($this->__params['time'])	? $this->__params['time'] : '';
		$key		= isset($this->__params['key'])		? $this->__params['key'] : '';
		
		$request_ids	= isset($this->__params['request_ids'])		? $this->__params['request_ids'] : array();
		$access_token	= isset($this->__params['access_token'])	? $this->__params['access_token'] : '';
		
		if($key != md5("{$sitemid}bottle{$time}")) die('unaccess'); 

		$d = mdl_account_basic::getInstance()->get('', $sitemid);
		if(empty($d)) {
			
			$invite_uid = '';
			
			// check request ids;
			if(!empty($request_ids)) {
				$request_id = array_pop($request_ids); // 直接取最後一個, 因為是最新的
				$o = json_decode(file_get_contents("https://graph.facebook.com/{$request_id}?access_token={$access_token}"), true);
				list(, $invite_sitemid, $flag) = isset($o['data']) ? explode('.', $o['data']) : array('', '', 0);
				
				if(!empty($invite_sitemid)) {
					$x = mdl_account_basic::getInstance()->get('', $invite_sitemid);
					$invite_uid = isset($x['uid']) ? $x['uid'] : '';	
				}
				
				if(!empty($invite_uid)) { // 增加相應額度
					switch($flag) {
					// 撈
					case '0': mdl_account_basic::getInstance()->mod($invite_uid, '', '', $x['pick'] + 1); break;
					// 扔
					case '1': mdl_account_basic::getInstance()->mod($invite_uid, '', '', '', $x['wine'] + 1); break;
					}
				}
			}
			
			$d = mdl_account_basic::getInstance()->makeAccount($sitemid, $invite_uid);
		}
		
		$uid = $d['uid'];
		
		$d_limit = mdl_account_limit::getInstance()->get($uid, TODAY);
		if(empty($d_limit) && mdl_account_limit::getInstance()->init($uid, $d['pick'], $d['wine'])) {
			$d_limit['wine'] = $d['wine'];
			$d_limit['pick'] = $d['pick'];
		}
		
		$data = array(
			'uid'				=> $uid,
			'wine_cooler'		=> $d_limit['wine'],
			'pick'			=> $d_limit['pick'],
		);
		$this->output($data);
	}
	
	function update() { // 更新用户昵称及其他信息
		
	}
}